package com.zdj.stream;

import lombok.Data;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author zhangdj
 */
@Data
public class StreamTest {

    private  static List<User> userList = new ArrayList<>();

    @Test
    public void map() {
        for (int i = 0; i < 5; i++) {
            User user = new User(i, "name" + i, "address" + i, "phone" + i);
            userList.add(user);
        }
        System.out.println(userList);
        List<String> stringList = userList.stream().map(User::getUserName).collect(Collectors.toList());
        System.out.println(stringList);
    }

    @Test
    public void flatMapTest() {
        List<String> list = Arrays.asList("Hello", "World");
        List<String> collect = list.stream().map(a -> a.split("")).flatMap(Arrays::stream).collect(Collectors.toList());
        System.out.println(collect);
    }

    @Test
    public void peekTest() {
        Stream.of("one", "two", "three", "four")
                .filter(e -> e.length() > 3)
                .peek(e -> System.out.println("Filtered value: " + e))
                .map(String::toUpperCase)
                .peek(e -> System.out.println("Mapped value: " + e))
                .collect(Collectors.toList());
    }

    /**
     * identity作为初始值，执行传入的方法
     */
    @Test
    public void reduceTest() {
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        // 加法
        System.out.println(list.stream().reduce(-1, Integer::sum));
        // 乘法
        System.out.println(list.stream().reduce(2, (a , b) -> a * b));
        // 拼串
        List<String> stringList = new ArrayList<>();
        stringList.add("a");
        stringList.add("b");
        System.out.println(stringList.stream().reduce("c", (a, b) -> a + b));
    }

}
